﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace CashFlow.Web.MyActionResult
{
    public class NullToEmptyStringResolver
        : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type
            , MemberSerialization memberSerialization)
        {
            return type.GetProperties()
                       .Select(p =>
                        {
                            var jp = base.CreateProperty(p, memberSerialization);
                            jp.ValueProvider = new NullToEmptyStringValueProvider(p);
                            return jp;
                        })
                       .ToList();
        }
    }

    public class NullToEmptyStringValueProvider : IValueProvider
    {
        PropertyInfo _MemberInfo;

        public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
        {
            _MemberInfo = memberInfo;
        }

        public object GetValue(object target)
        {
            object result = _MemberInfo.GetValue(target);
            if (result == null
                && _MemberInfo.PropertyType.ToString() == "System.String")
            {
                result = "";
            }
            return result;

        }

        public void SetValue(object target, object value)
        {
            _MemberInfo.SetValue(target, value);
        }
    }
}